/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       joint.cpp
 * Author:     twoja stara
 * Created on: 2009-09-24
 *
 **********************************************************************************************************************/

#include "joint.h"
#include "actor.h"

namespace mGameEngine
{
namespace Physics
{

Joint::Joint() :
    _actor1(NULL), _actor2(NULL),
    _anchor1(), _anchor2(),
    _created(false), _joint(NULL)
{
}

Joint::~Joint()
{
    // remove joint from actors
    Actor *tmp1 = _actor1, *tmp2 = _actor2;
    _actor1 = _actor2 = NULL;
    if(tmp1)
    {
        tmp1->removeJoint(this);
    }
    if(tmp2)
    {
        tmp2->removeJoint(this);
    }

    // release physX joint
    if(_joint)
    {
        _joint->getScene().releaseJoint(*_joint);
    }
}

void Joint::setFirstActor(Actor *actor)
{
    // no NULL actors or already joined actors
    if(!actor || actor == _actor1 || actor == _actor2)
    {
        return;
    }

    // remove from previous actor
    if(_actor1)
    {
        _actor1->removeJoint(this);
    }

    // set new actor
    _actor1 = actor;
    _actor1->addJoint(this, _actor2);
}

void Joint::setSecondActor(Actor *actor)
{
    // no NULL actors or already joined actors
    if(!actor || actor == _actor1 || actor == _actor2)
    {
        return;
    }

    // remove from previous actor
    if(_actor2)
    {
        _actor2->removeJoint(this);
    }

    // set new actor
    _actor2 = actor;
    _actor2->addJoint(this, _actor1);
}

void Joint::setFirstActorAnchor(const Matrix4x4 &anchor)
{
    _anchor1 = anchor;

    if(_joint)
    {
        // TODO probably will be pure virtual..
        // meanwhile, dynamic changing of anchor is not possible
    }
}

void Joint::setSecondActorAnchor(const Matrix4x4 &anchor)
{
    _anchor2 = anchor;

    if(_joint)
    {
        // TODO probably will be pure virtual..
        // meanwhile, dynamic changing of anchor is not possible
    }
}

}
}

